package com.solocredit.finance.data.dev.take

import android.Manifest
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import com.google.gson.Gson
import com.solocredit.finance.data.dev.utils.gzipString

/**
 * AppList
 */
class TakeFlexiMolaApp(val context: Context) {

    fun takeFlexiMolaApp(): String? {
        return try {
            val array = arrayOf(
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE
            )

            val flags = PackageManager.GET_ACTIVITIES or PackageManager.GET_META_DATA
            val packages = context.packageManager.getPackagesHoldingPermissions(array, flags)

            val appList = mutableListOf<HashMap<String, Any>>()
            for (packageInfo in packages) {
                val appInfo = packageInfo.applicationInfo

                appInfo?.let {

                    // 过滤掉系统应用
                    val cSY = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0)
                    if (!cSY) {
                        val appName = appInfo.loadLabel(context.packageManager).toString()
                        val appVersionCode = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                            packageInfo.versionCode.toString()
                        } else {
                            packageInfo.longVersionCode.toString()
                        }

                        val jsonObject = HashMap<String, Any>().apply {
                            put("appType", 0)
                            put("appName", appName)
                            put("appVersionCode", appVersionCode)
                            put("dataPath", appInfo.dataDir ?: "")
                            put("sourcePath", appInfo.sourceDir ?: "")
                            put("appPackageName", packageInfo.packageName ?: "")
                            put("appVersionName", packageInfo.versionName ?: "")
                            put("installTime", packageInfo.firstInstallTime.toString())
                            put("lastTime", packageInfo.lastUpdateTime.toString())
                            put("flags", appInfo.flags.toString())
                        }
                        appList.add(jsonObject)
                    }
                }
            }

            Gson().toJson(appList).trim().gzipString()

        } catch (e: Exception) {
            null
        }
    }
}